/* eslint-disable array-callback-return */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, DatePicker, Table, Modal, Input, message, Button } from 'antd';
import Link from 'umi/link';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import FooterToolbar from '@/components/FooterToolbar';
import DescriptionList from '@/components/DescriptionList';

const { Description } = DescriptionList;
const FormItem = Form.Item;
const { MonthPicker } = DatePicker;
@connect(({ reducemprec, loading }) => ({
  datar: reducemprec.datar,
  ordCutPdList: reducemprec.reducemprec,
  loading: loading.models.reducemprec,
  payDetailsData: reducemprec.payDetailsData,
}))
@Form.create()
class TableList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      ordCutSetList: [],
      ordCutPdList: [],
      modalVisible: false,
      timeStart: null,
      recvTaskId: null,
      recvOrdPdId: '',
      recvOrdSetId: '',
      switchFlag: true,
      mapjis: true,
      currentDate: '',
      maistrue: false,
      isModify: '',
      disabledEndDate: null,
    };
  }

  componentDidMount() {
    const { dispatch, location } = this.props;
    const { recvOrdAddTaskId } = location.query;
    const { isModify } = location.query;
    this.setState({
      recvTaskId: recvOrdAddTaskId,
      isModify,
    });
    dispatch({
      type: 'reducemprec/receiptback',
      payload: { recvOrdCutTaskId: recvOrdAddTaskId },
    });
  }

  // 修改
  update = record => {
    const { form } = this.props;
    form.resetFields();
    this.setState({
      modalVisible: true,
      timeStart: record.endDate,
      recvOrdSetId: record.recvOrdAddSetId ? record.recvOrdAddSetId : '',
      recvOrdPdId: record.recvOrdCutPdId ? record.recvOrdCutPdId : '',
      recvOrdCutSetId: record.recvOrdCutSetId ? record.recvOrdCutSetId : '',
      disabledEndDate: record.oldEndDate || null,
    });
  };

  // 模态框显隐
  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  changetime = e => {
    const time = moment(e).format('YYYY-MM');
    const arr = time.split('-');
    const seperator = '-';
    const newtime = new Date(arr[0], arr[1], 1);
    const currentDate =
      arr[0] +
      seperator +
      arr[1] +
      seperator +
      new Date(newtime.getTime() - 1000 * 60 * 60 * 24).getDate();
    this.setState({
      currentDate,
    });
  };

  // 回单
  receipt = record => {
    const { dispatch, location, datar } = this.props;
    dispatch({
      type: 'reducemprec/receiptId',
      payload: record.pdId
        ? { pdId: record.pdId, recvOrdCutTaskId: datar.recvOrdCutTaskId }
        : { ass: record.ass, recvOrdCutTaskId: datar.recvOrdCutTaskId },
      // payload: {recvOrdAddSetId:record.pdId},
      callback: response => {
        if (response.success) {
          message.success('回单成功！');
          const { recvOrdAddTaskId } = location.query;

          this.setState({
            recvTaskId: recvOrdAddTaskId,
            switchFlag: true,
          });
          dispatch({
            type: 'reducemprec/receiptback',
            payload: { recvOrdCutTaskId: recvOrdAddTaskId },
          });
        } else {
          message.warning('回单失败!');
          const { recvOrdAddTaskId } = location.query;

          this.setState({
            recvTaskId: recvOrdAddTaskId,
            switchFlag: true,
          });
          dispatch({
            type: 'reducemprec/receiptback',
            payload: { recvOrdCutTaskId: recvOrdAddTaskId },
          });
        }
      },
    });
  };

  // 分项回单
  subsett = record => {
    const { ordCutSetList, ordCutPdList, switchFlag, mapjis } = this.state;
    const { dispatch } = this.props;
    if (switchFlag) {
      if (mapjis) {
        if (ordCutSetList) {
          ordCutSetList.map(item => {
            const temp = item;
            temp.pdName = temp.assName;
            temp.cityName = record.cityName;
            temp.editFlagName = record.editFlagName;
            temp.ass = temp.ass;
            temp.editFlag = record.editFlag;
            temp.recvOrdAddSetId = temp.recvOrdAddSetId;
            ordCutPdList.splice(1, 0, temp);
          });
        }

        // this.setState({
        //   mapjis: false,
        // });
      }
      const ll = [];
      ordCutPdList.map(item => {
        if (item.recvOrdCutPdId) {
          ll.push(item);
        }
      });
      dispatch({
        type: 'reducemprec/addordCutPdList',
        payload: ordCutPdList,
      });
      this.setState({
        ordCutPdList,
        switchFlag: false,
      });
    } else {
      this.setState({
        ordCutPdList,
        switchFlag: true,
      });
      const ll = [];
      ordCutPdList.map(item => {
        if (item.pdId) {
          ll.push(item);
        }
      });
      dispatch({
        type: 'reducemprec/newpdInfoDtosList',
        payload: ll,
      });

      this.setState({
        ordCutPdList,
        switchFlag: true,
      });
    }
  };

  // 缴纳明细弹框
  detailed = () => {
    const { dispatch, location } = this.props;
    const { recvOrdAddTaskId } = location.query;
    dispatch({
      type: 'reducemprec/getPaymentDetails',
      payload: { recvOrdAddTaskId },
    });

    this.setState({
      maistrue: true,
    });
  };

  // 关闭缴纳明细弹框
  handleOk = () => {
    this.setState({
      maistrue: false,
    });
  };

  // 禁用日期
  disabledDate = (startValue, limitDate) => startValue.valueOf() > moment(limitDate).valueOf();

  // 修改提交
  submitData = () => {
    const { dispatch, form } = this.props;
    const { recvOrdPdId, recvTaskId, recvOrdSetId, recvOrdCutSetId, switchFlag } = this.state;
    const getFieldsList = form.getFieldsValue();
    form.validateFields(err => {
      if (!err) {
        const times = getFieldsList.bigenTime ? getFieldsList.bigenTime.format('YYYYMM01') : null;
        const end = moment(times)
          .add('month', 1)
          .add('days', -1)
          .format('YYYYMMDD');

        let paramet = {};
        if (recvOrdPdId.length > 0) {
          paramet = {
            recvEndYm: end,
            remark: getFieldsList.product,
            recvOrdTaskId: recvTaskId,
            recvOrdPdId,
          };
        } else {
          paramet = {
            recvEndYm: end,
            remark: getFieldsList.product,
            recvOrdTaskId: recvTaskId,
            recvOrdSetId,
          };
        }
        if (!switchFlag) {
          paramet = {
            ...paramet,
            recvOrdCutSetId,
          };
        }
        dispatch({
          type: 'reducemprec/modification',
          payload: paramet,
          callback: response => {
            if (response.success) {
              message.success('修改成功！');
              this.handleModalVisible(false);

              this.setState({
                switchFlag: true,
              });
              dispatch({
                type: 'reducemprec/receiptback',
                payload: { recvOrdCutTaskId: recvTaskId },
              });
              // dispatch({
              //   type: 'reducemprec/receiptback',
              //   payload: { recvOrdCutTaskId: recvOrdAddTaskId },
              // });
            } else {
              message.warning('修改失败!');
              this.handleModalVisible(false);
              this.setState({
                switchFlag: true,
              });
              dispatch({
                type: 'reducemprec/receiptback',
                payload: { recvOrdCutTaskId: recvTaskId },
              });
            }
          },
        });
      }
    });
    // Receipt modification
    // console.log(paramet)
  };

  render() {
    // const { datar, loading, form: { getFieldDecorator }} = this.props;
    const {
      modalVisible,
      timeStart,
      currentDate,
      ordCutPdList,
      maistrue,
      isModify,
      switchFlag,
      disabledEndDate,
    } = this.state;
    const ll = [];
    const {
      datar,
      form: { getFieldDecorator },
      payDetailsData,
    } = this.props;
    const newordCutPdList = [];
    if (datar.ordCutPdList) {
      datar.ordCutPdList.map(pditem => {
        if (pditem.receFlag !== 1) {
          newordCutPdList.push(pditem);
        }
      });
    }
    const columns = [
      {
        title: '产品',
        dataIndex: 'pdName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '执行地',
        dataIndex: 'cityName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      // {
      //   title: '业务开始日期',
      //   dataIndex: 'sendBeginDate',
      //   onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      //   render: val => val && `${val.toString().substr(0, 4)}-${val.toString().substr(4, 5)}`,
      //   // render: sendBeginDate => {
      //   //   return moment(sendBeginDate).format('YYYY-MM-DD');
      //   // },
      // },
      {
        title: '业务结束日期',
        dataIndex: 'endDate',
        align: 'center',
        // sorter: (a, b) => new Date(b.beginDate) - new Date(a.beginDate),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        // render: val => (val ? moment(val).format('YYYY-MM') : '无'),
        // render: val => val && `${val.toString().substr(0, 4)}-${val.toString().substr(4, 5)}`,
        render: val => {
          if (val && val && moment(val).format('YYYY-MM-01')) {
            const start = val && moment(val).format('YYYY-MM-01');
            const end = moment(start)
              .add('month', 1)
              .add('days', -1)
              .format('YYYY-MM-DD');
            return end;
          }
          return '--';
        },
      },
      // {
      //   title: '有无修改',
      //   dataIndex: 'editFlagName',
      // },
      {
        title: '修改说明',
        dataIndex: 'editDesc',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => {
          if (val) {
            return val;
          }
          return '--';
        },
      },

      {
        title: '操作',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => (
          <div>
            {String(record.pdId) === 'PDINF_0000000001' ? (
              <div>
                {Number(isModify) === 2 ? (
                  <a
                    style={{ marginRight: '10px' }}
                    onClick={() => {
                      this.receipt(record);
                    }}
                  >
                    回单
                  </a>
                ) : null}

                <a
                  style={{ marginRight: '10px' }}
                  onClick={() => {
                    this.update(record);
                  }}
                >
                  修改
                </a>
                {switchFlag ? (
                  <a
                    onClick={() => {
                      this.subsett(record);
                    }}
                  >
                    分项回单
                  </a>
                ) : (
                  <a
                    onClick={() => {
                      this.subsett(record);
                    }}
                  >
                    取消分项回单
                  </a>
                )}
              </div>
            ) : (
              <div>
                {Number(isModify) === 2 ? (
                  <a
                    style={{ marginRight: '10px' }}
                    onClick={() => {
                      this.receipt(record);
                    }}
                  >
                    回单
                  </a>
                ) : null}

                <a
                  onClick={() => {
                    this.update(record);
                  }}
                >
                  修改
                </a>
              </div>
            )}
          </div>
        ),
      },
    ];

    const startTimes = timeStart && moment(timeStart).format('YYYY-MM-01');
    const endTimes = moment(startTimes)
      .add('month', 1)
      .add('days', -1)
      .format('YYYY-MM-DD');
    this.setState({
      ordCutSetList: datar.ordCutSetList,
      ordCutPdList: datar.ordCutPdList,
    });
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };
    const formItemLayouts = {
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
    };

    const insAccuColumns = [
      {
        title: '产品名称',
        dataIndex: 'assName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '业务开始日期',
        dataIndex: 'beginDate',
        align: 'center',
        // sorter: (a, b) => new Date(b.beginDate) - new Date(a.beginDate),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => (val ? moment(val).format('YYYY-MM-01') : '--'),
        // render: val => val && `${val.toString().substr(0, 4)}-${val.toString().substr(4, 5)}`,
      },
      {
        title: '业务结束日期',
        dataIndex: 'endDate',
        align: 'center',
        sorter: (a, b) => new Date(b.endDate) - new Date(a.endDate),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        // render: val => (val ? moment(val).format('YYYY-MM') : '无'),
        render: val => {
          if (val && val && moment(val).format('YYYY-MM-01')) {
            const start = val && moment(val).format('YYYY-MM-01');
            const end = moment(start)
              .add('month', 1)
              .add('days', -1)
              .format('YYYY-MM-DD');
            return end;
          }
          return '--';
        },
      },
      {
        title: '缴纳金额',
        dataIndex: 'payAmount',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
        render: val => val || (val === 0 ? 0 : null),
      },
      {
        title: '企业基数',
        dataIndex: 'entpBase',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
        render: val => val || (val === 0 ? 0 : null),
      },
      {
        title: '企业比例(%)',
        dataIndex: 'entpProp',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val || (val === 0 ? 0 : null),
      },
      {
        title: '企业附加(元)',
        dataIndex: 'entpAddnAmo',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
        render: val => val || (val === 0 ? 0 : null),
      },
      {
        title: '企业缴费',
        dataIndex: 'entpPay',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
        render: val => val || (val === 0 ? 0 : null),
      },
      {
        title: '个人基数',
        dataIndex: 'perBase',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
        render: val => val || (val === 0 ? 0 : null),
      },
      {
        title: '个人比例(%)',
        dataIndex: 'perProp',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val || (val === 0 ? 0 : null),
      },
      {
        title: '个人附加(元)',
        dataIndex: 'perAddnAmo',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
        render: val => val || (val === 0 ? 0 : null),
      },
      {
        title: '个人缴费',
        dataIndex: 'perPay',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
        render: val => val || (val === 0 ? 0 : null),
      },
      {
        title: '执行地区',
        dataIndex: 'cityName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
    ];
    return (
      <PageHeaderWrapper>
        <Card
          title={
            <span style={{ fontWeight: 'bolder' }} id="sendInfor">
              员工信息
            </span>
          }
          bordered={false}
        >
          {datar.recvOrdInfoDetailDto ? (
            <DescriptionList>
              <Description term="姓名">{datar.recvOrdInfoDetailDto.empName || '--'}</Description>
              <Description term="证件类型">
                {datar.recvOrdInfoDetailDto.idTypeName || '--'}
              </Description>
              <Description term="证件号">{datar.recvOrdInfoDetailDto.idCode || '--'}</Description>
              <Description term="国籍">{datar.recvOrdInfoDetailDto.nationName || '--'}</Description>
              <Description term="出生日期">
                {moment(datar.recvOrdInfoDetailDto.birthDate).format('YYYY-MM-DD') || '--'}
              </Description>
              <Description term="性别">{datar.recvOrdInfoDetailDto.genderName || '--'}</Description>
              <Description term="电话">{datar.recvOrdInfoDetailDto.mobile || '--'}</Description>
              <Description term="员工邮箱">{datar.recvOrdInfoDetailDto.email || '--'}</Description>
            </DescriptionList>
          ) : null}
          <div style={{ borderBottom: '1px dashed #ccc', margin: '20px 0' }} />
          <div style={{ marginTop: 24 }} bordered={false}>
            {datar.recvOrdInfoDetailDto ? (
              <DescriptionList>
                {/* <Description term="客户名称">{datar.recvOrdInfoDetailDto.custName}</Description> */}
                <Description term="签约方">
                  {datar.recvOrdInfoDetailDto.sendSuppName || '--'}
                </Description>
                <Description term="客户名称">
                  {datar.recvOrdInfoDetailDto.custName || '--'}
                </Description>
                <Description term="离职日期">
                  {moment(datar.recvOrdInfoDetailDto.evaDate).format('YYYY-MM-DD') || '--'}
                </Description>
                <Description term="是否离职联系">
                  {datar.recvOrdInfoDetailDto.reduConEmpFlagName || '--'}
                </Description>
                <Description term="是否办理失业">
                  {datar.recvOrdInfoDetailDto.unempFlagName || '--'}
                </Description>
                <Description term="社保停做原因">
                  {datar.recvOrdInfoDetailDto.evaReason || '--'}
                </Description>
              </DescriptionList>
            ) : null}
          </div>
        </Card>
        <Card
          style={{ marginTop: '20px' }}
          title={
            <span style={{ fontWeight: 'bolder' }} id="sendInfor">
              减少产品
            </span>
          }
          bordered={false}
        >
          <div>
            {ordCutPdList
              ? ordCutPdList.map(item => {
                  if (item.recvOrdCutPdId) {
                    ll.push(item);
                  }
                })
              : null}
          </div>
          <Table
            columns={columns}
            // dataSource = {this.state.switchFlag == true ? ll : this.state.ordCutPdList}
            // dataSource={this.state.ordCutPdList}

            // dataSource={datar.ordCutPdList}

            dataSource={newordCutPdList}
            pagination={false}
          />
        </Card>
        <Modal
          width={800}
          title="修改"
          visible={modalVisible}
          okText="确定"
          cancelText="取消"
          onOk={this.submitData}
          onCancel={() => this.handleModalVisible(false)}
        >
          {/* <Form>
            <div style={{ float: 'left', width: '250px' }}>
              <p>签约方：</p>
              <p>业务开始日期：{moment(this.state.timeStart).format('YYYY-MM-DD')}</p>
              render: val => val && `${val.toString().substr(0, 4)}-${val.toString().substr(4, 5)}`,
              <p>
                业务结束日期：
                {this.state.timeStart == ''
                  ? null
                  : `${this.state.timeStart
                      .toString()
                      .substr(0, 4)}-${this.state.timeStart.toString().substr(4, 5)}`}
              </p>
            </div>
            <div style={{ float: 'left', width: '400px' }}>
              <p>接单方：</p>
              <FormItem {...formItemLayout} label="业务结束日期">
                {getFieldDecorator('bigenTime', {
                  rules: [{ required: true, message: '请选择' }],
                })(<MonthPicker />)}
              </FormItem>
              <FormItem {...formItemLayout} label="变更说明">
                {getFieldDecorator('product', {
                  rules: [{ required: true, message: '请输入' }],
                })(<Input placeholder="请输入" maxLength={100} />)}
              </FormItem>
            </div>




          </Form> */}

          <Form>
            <div style={{ float: 'left', width: '350px' }}>
              <p style={{ lineHeight: '1px' }}>
                签约方：
                {datar.recvOrdInfoDetailDto && datar.recvOrdInfoDetailDto.sendSuppName
                  ? datar.recvOrdInfoDetailDto.sendSuppName
                  : '--'}
              </p>
              <p style={{ margin: '45px 0 0 0' }}>
                业务结束日期：
                {timeStart == null || String(timeStart) === 'undefined' ? null : endTimes}
              </p>
            </div>
            <div style={{ float: 'left', width: '350px' }}>
              <p style={{ lineHeight: '1px', margin: '0 0 40px 0' }}>
                接单方：
                {datar.recvOrdInfoDetailDto && datar.recvOrdInfoDetailDto.recvSuppName
                  ? datar.recvOrdInfoDetailDto.recvSuppName
                  : '--'}
              </p>
              <FormItem {...formItemLayouts} label="业务结束日期">
                {getFieldDecorator('bigenTime', {
                  rules: [{ required: true, message: '请选择' }],
                })(
                  <MonthPicker
                    onChange={e => this.changetime(e)}
                    format={currentDate}
                    disabledDate={startValue => this.disabledDate(startValue, disabledEndDate)}
                  />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="变更说明">
                {getFieldDecorator('product', {
                  rules: [{ required: true, message: '请输入' }],
                })(<Input placeholder="请输入" maxLength={100} />)}
              </FormItem>
            </div>
          </Form>
        </Modal>
        <FooterToolbar style={{ width: '100%' }}>
          <Link to="/receiveordermanage/reduceemployee/index">
            <Button
              // onClick={() => router.push(`/supplymanage/protection/index?activeKey=${activeKey}`)}
              style={{ marginRight: 10 }}
            >
              关闭
            </Button>
          </Link>
        </FooterToolbar>
        <Modal
          width="1200px"
          visible={maistrue}
          onCancel={this.handleOk}
          title="社保公积金明细"
          footer={[
            <Button key="submit" type="primary" onClick={this.handleOk}>
              关闭
            </Button>,
          ]}
        >
          <Card>
            <Table
              // scroll={scroll}
              dataSource={payDetailsData}
              columns={insAccuColumns}
              rowKey={record => record.serSetId}
              // loading={loading}
              pagination={false}
              // pagination={moreFlagList[parseInt(activeKey) - 1] == '2' ? false : pagination}
            />
          </Card>
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default TableList;
